package cn.com.dhcc.turbo.web.controller.exch;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.turbo.entity.registry.ExchConnRequest;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.exch.exhmgr.ExchConnRequestService;
import cn.com.dhcc.turbo.service.registry.sync.webservice.NodeCommunicateClient;
import cn.com.dhcc.turbo.service.registry.vo.NodeExchRelVo;

/**
 * 请求审核Controller
 * 
 * @日期：2014-5-19 下午2:09:28
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/exch")
public class ExchConnRequestController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);
	@Autowired
	private ExchConnRequestService exchConnRequestService;
	@Autowired
	private NodeCommunicateClient nodeCommunicateClient;

	/**
	 * 获取请求审核信息列表
	 * 
	 * @param model
	 * @param pager
	 * @param searchName
	 * @param searchNodeName
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/conn_request_list", method = RequestMethod.GET)
	public String list(Model model,HttpSession httpSession, Pager pager, String searchName,
			String searchNodeName) {
		WhereCondition condition = new WhereCondition();
		condition.orderBy("status desc,mtime asc");
		try {

			PagerData<ExchConnRequest> pagerData = exchConnRequestService.list(
					pager, condition);
			List<ExchConnRequest> list = new ArrayList<ExchConnRequest>();
			if(pagerData.getDatas() != null){
				for (Iterator iterator = pagerData.getDatas().iterator(); iterator.hasNext();) {
					ExchConnRequest conn = (ExchConnRequest) iterator.next();
					String requestContent =conn.getRequestContent();
					NodeExchRelVo  connRequest =JsonUtil.toObject(requestContent,NodeExchRelVo.class);
					NodeInfo node = connRequest.getFromNode();
					conn.setFromNodeName(node.getNodeName());
					list.add(conn);
				}
			}
			model.addAttribute(DATA_KEY, list);
			setTotoal(model, pagerData.getTotal());
			UserInfo user = (UserInfo)getCurrentUserInfo(httpSession);
			if(user != null){
				model.addAttribute("nodeAdmin", user.getUserType());
			}
		} catch (Exception e) {
			logger.error("获取请求审核失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "exch/conn_request_list";
	}

	@RequestMapping(value = "/conn_request_audit")
	public String connRequestAudit(Model model,HttpServletRequest request,String id) {
		try {
			ExchConnRequest vo = exchConnRequestService.get(id);
			String requestContent =vo.getRequestContent();
			NodeExchRelVo  connRequest =JsonUtil.toObject(requestContent,NodeExchRelVo.class);
			
			model.addAttribute(DATA_KEY, connRequest.getFromNode());
			model.addAttribute("mtime", vo.getMtime());
			model.addAttribute("selectid", id);
			return "exch/conn_request_audit";
		} catch (Exception e) {
			logger.error("获取请求审核失败", e);
			return toAlertPage(model, e.getMessage());
		}
		
	}
	/**
	 *审核详情
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/conn_request_detail")
	public String connRequestDetail(HttpServletRequest request, Model model,String selectedNodeId,String selectid) {
		try {
			ExchConnRequest vo = exchConnRequestService.get(selectid);
			Map<String, NodeInfo> nodeInfoMap = new HashMap<String, NodeInfo>();
			String requestContent =vo.getRequestContent();
			List<NodeInfo> nodeInfoList = JsonUtil.toObjectList(requestContent, NodeInfo.class);
			for (NodeInfo node : nodeInfoList) {
				nodeInfoMap.put(node.getId(), node);
			}
			model.addAttribute("nodeInfo", nodeInfoMap.get(selectedNodeId));
			return "exch/conn_request_detail";
		} catch (Exception e) {
			return toAlertPage(model, "获取审核详情失败");
		}
	}
	
	/**
	 * 审核请求
	 * @param model
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/audit_conn_request")
	@ResponseBody
	public Map<String, Object> auditConnRequest(Model model, String id,String status,String response) {
		String msg = "";
		try {
			ExchConnRequest vo = exchConnRequestService.get(id);
			vo.setStatus(status);
			vo.setMtime(new Date());
			vo.setResponse(response);
			exchConnRequestService.update(vo);
			if("1".equals(vo.getStatus())){
				nodeCommunicateClient.exchRelRequestPass(vo.getId());
			}else{
				nodeCommunicateClient.exchRelRequestBlock(vo.getId(),vo.getResponse());
			}
			msg = "审核成功";
			return jsonSuccessResult(msg);
		}catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		} catch (Exception e) {
			msg = "审核失败";
			return jsonFailResult(msg);
		}
	}
	/**
	 * 请求查看
	 * @param id
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/conn_request_get")
	public String get(  Model model,HttpServletRequest request,String id) {
		try {
			ExchConnRequest vo = exchConnRequestService.get(id);
			String response = vo.getResponse();
			String requestContent =vo.getRequestContent();
			
			NodeExchRelVo  connRequest =JsonUtil.toObject(requestContent,NodeExchRelVo.class);
			NodeInfo node = connRequest.getFromNode();
			
			model.addAttribute(DATA_KEY, node);
			model.addAttribute("mtime", vo.getMtime());
			model.addAttribute("response", response);
			model.addAttribute("selectid", id);
			return "exch/conn_request_detail";
		} catch (Exception e) {
			logger.error("获取请求审核失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}
	/**
	 * 节点发起审核请求
	 * @param model
	 * @param nodeInstallUrl
	 * @return
	 */
	@RequestMapping(value = "/send_exch_rel_request", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object>  sendExchRelRequest( Model model,String nodeInstallUrl) {
			try {
				nodeCommunicateClient.sendExchRelRequest(nodeInstallUrl.trim());
			return jsonSuccessResult("请求已发出，请联系目的节点管理员审核！");
		} catch (NiceException e) {
			return jsonFailResult("请求失败,"+e.getMessage());
		}catch (Exception e) {
			return jsonFailResult("请求失败");
		}
	}
}
